<?php

/**
 * Description of consultant
 * @author Pham Minh Khoi
 * @email: pmkhoi@gmail.com
 * @package:
 **/

class Configsite extends MY_Controller {

    function __construct() {
        parent::__construct();

        $this->checkLogin();
        //$this->checkPermission();
        $this->load->model('config_model', 'configsite', true);
       // $this->load->model('tcategory_model', 'tcategory', true);
        //$this->load->model('country_model', 'country', true);
        //$this->load->model('province_model', 'province', true);
        //$this->load->model('consultant_type_model', 'type', true);
        $this->load->model('upload_files_model', 'file', true);
        //$this->load->model('province_consultant_model', 'consultant_province', true);
        $this->load->helper('form');
        $this->template->set_template('admin');
        $this->buildMenu();
        $this->template->add_js('js/jquery1.6.1.js');
        $this->template->add_js('js/ckeditor/plugins/htmlwriter/plugin.js');
        //$this->template->add_js('js/jquery1.6.1.js', 'embed');
    }

    function index() {
        $this->view();
    }

    function view($id_country = 0) {
        $this->load->library('pagination');
        
        //$base_url = $this->base_url . 'admin/product/view/' . $category . '/';
        $base_url = $this->base_url . 'admin/consultant/view/' . $id_country . '/';

        $data['rows'] = $this->configsite->getAll();
        $index = 0;
        foreach ($data['rows'] as &$row) {
            //$row['name'] = $row['title'];
            //if (file_exists(UPLOAD_IMAGE_PATH . $row['image']))
             //   $row['image'] = '<img src="' . base_url() . UPLOAD_IMAGE_PATH . $row['image'] . '" with="60px" height="60px">';
            //$row['check_active'] = $row['active'] == 1 ? "checked" : "";

            if ($index % 2 == 0)
                $row['css_class'] = 'row1';
            else
                $row['$css_class'] = 'row2';
            $index++;
        }

       

        $data['base_url'] = base_url();
         $data['path'] = base_url() . UPLOAD_BACKGROUND;

        //$data['ddlCategory'] = $this->buidDDProductCategoryList('category', $code_category, 'onchange="loadProduct()"');
        $this->template->parse_view('content', 'admin/configsite/view_configsite', $data);
        $this->template->render();
    }

    
    function do_upload($code)
    {
        $this->session->unset_userdata('images');
        $uploaddir = UPLOAD_BACKGROUND;

        $config['file_name'] =  time(). basename($_FILES['uploadfile']['name']); //date('Y-m-d H:i:s', time()).basename($_FILES['uploadfile']['name']);
        $config['upload_path'] = $uploaddir;
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
            //$config['overwrite'] = true;
            $config['max_size'] = 8192; // 8192 kb = 8mb
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';
            //$config['max_filename'] = 50;
            //$config['encrypt_name'] = true;
            //$config['remove_spaces'] = false;
            $result_upload = $this->uploadFile($config);
            if ($result_upload['error']) {

                //$error_message = $result_upload['message'];
               //echo "error";
               // echo $result_upload['message'];
                $data['error'] = true;
                echo 'error';
                //$data['cname'] = $info['cname'];
            } else if($result_upload['error'] == false){
                
                    $my_data['code'] = $code;
                    $my_data['value'] = $config['file_name'];
                    
                    $obj = $this->configsite->getByCode($code);
                    
                    if(!empty ($obj)){
                        @unlink(UPLOAD_BACKGROUND. $obj['value']);
                    }
                    
                    $this->configsite->update($my_data);
                            
                   

                //echo $config['file_name']; //"success";
                    echo $config['file_name'];
            }

            //echo json_encode($data);

    }

    function uploadFile($config) {

        $this->load->library('upload', $config);
        $result = array('error' => false);

        if (!$this->upload->do_upload('uploadfile')) {
            $result['message'] = $this->upload->display_errors();
            $result['error'] = true;
        } else {
            $result['upload_data'] = $this->upload->data();
            //print_r($result['upload_data']);
        }

        return $result;
    }

    function add_province($consultant_id = 0, $province_id = 0){
        //$consultant_id = intval($this->input->post('txtToutID'));
        //$province_id = intval($this->input->post('txtProvinceID'));

        $info = null;
        $data['consultant_id'] = $consultant_id;
        $data['province_id'] = $province_id;
        $result = array();
        if($consultant_id > 0){
            $item = $this->consultant_province->getById($consultant_id, $province_id);
            if(!empty ($item)){
                $result['error'] = true;
            }
            else{
                $affected_row = $this->consultant_province->insert($data);
                if($affected_row){

                    $result['error'] = false;
                    //$info =  $this->province->getById($province_id);
                    //$result['pname'] = $info['vi_name'];
                    //$result['cname'] = $info['cname'];
                }
                else
                    $result['error'] = true;
            }
        }
        else{
            $provinces = $this->session->userdata('provinces');
            if(!empty ($provinces)){
                if(array_key_exists($consultant_id+"_"+$province_id, $provinces))
                    $result['error'] = true;
                else{
                    $result['error'] = false;
                    $info =  $this->province->getById($province_id);

                    $provinces[$consultant_id+"_"+$province_id]['tid'] = $consultant_id;
                    $provinces[$consultant_id+"_"+$province_id]['pid'] = $province_id;
                    $provinces[$consultant_id+"_"+$province_id]['pname'] = $info['vi_name'];
                    $provinces[$consultant_id+"_"+$province_id]['cname'] = $info['cname'];
                    $this->session->set_userdata('provinces', $provinces);
                }
            }
            else{
                $result['error'] = false;
                $info =  $this->province->getById($province_id);

                $provinces[$consultant_id+"_"+$province_id]['tid'] = $consultant_id;
                $provinces[$consultant_id+"_"+$province_id]['pid'] = $province_id;
                $provinces[$consultant_id+"_"+$province_id]['pname'] = $info['vi_name'];
                $provinces[$consultant_id+"_"+$province_id]['cname'] = $info['cname'];
                $this->session->set_userdata('provinces', $provinces);
            }

        }


        if( $result['error'] == false){
            if(empty($info))
                $info =  $this->province->getById($province_id);
            //$result['error'] = false;
            $result['pname'] = $info['vi_name'];
            $result['cname'] = $info['cname'];
        }

       // $affected_row = $this->consultant_province->insert($data);
        echo json_encode($result);
    }

    function delete_location(){
        $consultant_id = intval($this->input->post('consultant_id'));
        $province_id = intval($this->input->post('province_id'));
        $provinces = $this->session->userdata('provinces');
        $result['error'] = true;
        if($consultant_id == 0){
            if(array_key_exists($consultant_id+"_"+$province_id, $provinces)){
                $result['error'] = false;
                unset ($provinces[$consultant_id+"_"+$province_id]);
                $this->session->set_userdata('provinces', $provinces);
            }
        }
        else{
            $affected_row = $this->consultant_province->delete($consultant_id, $province_id);
            $result['error'] = false;
        }

        echo json_encode($result);
    }

    function set_image(){
        $imageName = $this->input->post('image_name');
        $consultantID = $this->input->post('consultant_id');
        if($consultantID > 0){
            $resutl = $this->consultant->setImage($imageName, $consultantID);
            if($resutl){
                 $result['error'] = false;
            }
             $result['error'] = true;
        }
        else{
            $result['error'] = false;
            $this->session->set_userdata('image_default', $imageName);
        }

         echo json_encode($result);
    }

    function delete_image(){
        $imageName = $this->input->post('image_name');
        $consultantID = $this->input->post('consultant_id');
        $result['error'] = false;

        if($consultantID > 0){
            $_resutl = $this->file->deleteByName($imageName);

            $consultant  = $this->consultant->findByID($consultantID);
            if(!empty ($consultant) ){
                if($consultant['image'] == $imageName)
                    $this->consultant->setImage('', $consultantID);

            }

            if($_resutl){
                 $result['error'] = false;
            }
            else
             $result['error'] = true;



        }
        else{
            $result['error'] = false;
            $images = $this->session->userdata('images');
            for($i = 0; $i < count($images); $i++){
                if($images[$i] == $imageName ){
                    unset($images[$i]);
                    $image_default = $this->session->userdata('image_default');
                    if( $image_default == $imageName)
                        $this->session->unset_userdata('image_default');
                    break;
                }
            }
            $this->session->set_userdata('images', $images);

        }

        @unlink(UPLOAD_IMAGE_PATH.$imageName);

        echo json_encode($result);
    }

    function buidDDconsultantCategoryList($name, $default){
        //$this->load->model('pcategory_model', 'category', true);
        $categories = $this->tcategory->getAll(-1);
       // print_r($categories);
        //$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        //$name = 'Parent';
        $value = '';
        $selected = '';
        $space= '';
        $label = 'Parent';
        $class = '';
        $action = '';
        $style = '';

        $tmp = array();
        for($i = 0; $i <count($categories); $i++){
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->id_parent][$category->id] = $category;
        }

        //$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/*$categories*/, '', $default);
        $options = $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true) . $this->getCategoryOption($tmp/* $categories */, '0', $default);
        $data = array();
        $data['name'] = $name;
        $data['style'] = $style;
        $data['class'] = $class;
        $data['action'] = $action;
        $data['options'] = $options;
        return $this->load->view('admin/select', $data, true);
        //return eval($this->loadTemplate('admin/ddl.tpl'));
    }

    function getCategoryOption($tmp/*$categories*/, $parent = 0/*0*/, $default = 0/*0*/, $space = '&nbsp;'){
        $items = '';
        if(isset($tmp[$parent])){
            $num_record = count($tmp[$parent]);
            foreach($tmp[$parent] as $k => $v){
                //$parent = $v->id_pcategory;
                //$value = $v->id_pcategory;
                //echo '<br>\n'.$parent . '_\n';
                $parent = $v->id;
                $value = $v->id;
                $label = $v->vi_name;
                $selected = '';
                if($value == $default) $selected = 'selected';
                $items .= $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true);
                $items .=$this->getCategoryOption($tmp/* $categories */, $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }

        return $items;
    }

    function save(){
        $txtID = (int) trim($this->input->post('txtID'));
        $txtFriendlyUrl = trim($this->input->post('txtFriendlyURL'));

        $data = array();

        if ($txtID > 0){
            $consultant = $this->consultant->findByID($txtID);

            if (empty($consultant)) {
                redirect('admin/consultant/view');
                return;
            }

            $data = $consultant;
            $data['images'] =  $this->file->getFileByType($txtID, 1, 2);

        }
        else {
            $data['id'] = 0;
            $data['friendly_url'] = $txtFriendlyUrl;
            //$data['image'] = '';
            $images = $this->session->userdata('images');
            if(empty ($images))
                $images = array();
            $data['images'] = $images;
            $image = $this->session->userdata('image_default');
            if(empty ($image))
                $image = '';
            $data['image'] = $image;
            //print_r($images);
        }

        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        

       // $this->form_validation->set_rules('category', 'lang:category', 'callback_select_category_check');
       // $this->form_validation->set_message('code_check', '%s is not available.');
        $this->form_validation->set_rules('txtFullname', 'Họ tên', 'required|min_length[2]|max_length[120]');
            $this->form_validation->set_rules('txtAddress', 'Địa chỉ', 'required');
            $this->form_validation->set_rules('txtEmail', 'Email', 'required|valid_email');
            $this->form_validation->set_rules('txtPhone', 'Điện thoại', 'required|min_length[10]|max_length[11]');
            $this->form_validation->set_rules('txtFax', 'Fax', 'min_length[10]');
            $this->form_validation->set_rules('txtTitle', 'Tiêu đề', 'required|min_length[10]|max_length[80]');
            $this->form_validation->set_rules('txtQuestion', 'Nội dung', 'required|min_length[20]|max_length[3000]');
       // $this->form_validation->set_rules('txtDeparture', 'lang:departure', 'required|min_length[2]');
       // $this->form_validation->set_rules('txtPeriod', 'lang:period', 'required|min_length[2]');

        //if($txtLinkRewrite!='' AND $txtLinkRewrite!=$category->link_rewrite)
        //$this->form_validation->set_rules('txtLinkRewrite', 'lang:friendly_url', 'callback_friendly_url_check');
        /* $this->form_validation->set_rules('password', 'Password', 'required');
          $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
          $this->form_validation->set_rules('email', 'Email', 'required');
         */

        $data['fullname'] = $this->input->post('txtFullname');
        $data['address'] = $this->input->post('txtAddress');
        $data['email'] = $this->input->post('txtEmail');
        $data['phone'] = $this->input->post('txtPhone');
        $data['fax'] = $this->input->post('txtFax');
        $data['title'] = $this->input->post('txtTitle');
        $data['question'] = $this->input->post('txtQuestion');
        $data['answer'] = trim($this->input->post('txtAnswer'));
        
        if($data['answer'] != '')
                    $data['status'] = 2;
        else 
            $data['status'] = 1;
        
        $data['position'] = trim($this->input->post('txtPosition'));
        //$data['active'] = (int) $this->input->post('active');
       
        //$data['friendly_url'] = trim($this->input->post('txtFriendlyURL'));
        $data['active'] = (int)trim($this->input->post('ckActive'));
        
        $data['image'] = '';

        $data['visited'] = 0;
        $product->image = '';
        $data['add_date'] = date('Y-m-d H:i:s', time());
        $data['upd_date'] = date('Y-m-d H:i:s', time());

        $error_message = ''; // $this->loadErrorMessage('Thong diep loi.');
        //print_r($_POST);
        $attach_image = false;
        

        /* if($attach_image == true AND $image_upload['error']==true){
          echo 'Not is image'; return;
          } */

        if ($this->form_validation->run() == FALSE ) {

            $error_message = validation_errors() . '<br>' . $error_message;
            //$code = uniqid();
            //$this->session->set_userdata('code', $code);

           // $data = array();
          //  $data['news'] = $news;

        $data['ckActive'] = form_checkbox('ckActive', '1', $data['active']);

        $data['error_message'] = '<div style="color:red">' . $error_message . '</div>';
        //if()
        $data['legend_text'] = $txtID > 0 ? lang('edit_news') : lang('create_news');

        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');


         $config['toolbar'] = array(
          array( 'Source', '-', 'Bold', 'Italic', 'Underline', 'Strike' ),
          array( 'Image', 'Link', 'Unlink', 'Anchor' )
      );

        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $data['config'] = $config;
         $data['base_url'] = base_url();
            $this->template->parse_view('content', 'admin/consultant/create_consultant', $data);
            $this->template->render();

            return;
        } else {
            
            $result = 0;

            if ($txtID > 0) {
                
                    
                $result = $this->consultant->update($data);
            } else {
               // $data['date_add'] = date('Y-m-d H:i:s', time());
                $result = $this->consultant->create($data);
            }

            $images = $this->session->userdata('images');

            if ($txtID == 0 && $result > 0) {
                if(!empty($images) && count($images) > 0){

                $_images = array();
                for ($i = 0; $i < count($images); $i++) {
                    $name_image = $images[$i];
                    $image = new stdClass();
                    $image->item_id = $result;
                    $image->vi_file_name = $name_image['vi_file_name'];
                    $image->en_file_name = $name_image['vi_file_name'];
                    $image->vi_alias = '';
                    $image->en_alias = '';
                    $image->vi_description = '';
                    $image->en_description = '';
                    $image->position = $this->file->getMaxPosition() + 1;
                    $image->file_type = 1;
                    $image->item_type = 2;
                    $image->active = 1;
                    $image->add_date = date('Y-m-d H:i:s', time());
                    $image->upd_date = date('Y-m-d H:i:s', time());

                    $_images[] = $image;


                    }

                if (count($_images) > 0) {

                    $this->file->create($_images);

                }
                $this->session->unset_userdata('images');
                }

                
            }



            redirect('admin/consultant/view');
        }
    }

    function friendly_url_check($url) {
        $result = $this->consultant->getByFriendlyUrl($url);
        if ($result != null) {
            $this->form_validation->set_message('friendly_url_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function code_check($code) {
        $result = $this->consultant->getByCode($code);
        if ($result != null) {
            $this->form_validation->set_message('code_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

} // end class.

?>
